package com.whpost.service.service.stamp;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.config.Wdpz;
import com.whpost.service.dao.stamp.*;
import com.whpost.service.dao.t.TDelDao;
import com.whpost.service.dao.wx.TWxOrderDao;
import com.whpost.service.entity.stamp.*;
import com.whpost.service.entity.t.TCzy;
import com.whpost.service.entity.t.TDel;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.entity.wx.TWxOrder;
import com.whpost.service.service.BaseServices;
import com.whpost.service.service.stamp.h5.WxPay;
import com.whpost.service.service.t.FileService;
import com.whpost.service.service.t.TApiNonceService;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.tools.Url;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StampCardOrderServices extends BaseServices {

    @Resource
    private StampXmMapper stampXmMapper;
    @Resource
    private StampHdMapper stampHdMapper;
    @Resource
    private StampHdLxMapper stampHdLxMapper;
    @Resource
    private TApiNonceService tApiNonceService;
    @Resource
    private Wdpz wdpz;
    @Resource
    private FileService fileService;
    @Resource
    private StampCardMapper stampCardMapper;
    @Resource
    private StampCardOrderMapper stampCardOrderMapper;
    @Resource
    private TDelDao tDelDao;
    @Resource
    private TWxOrderDao tWxOrderDao;
    @Resource
    private WxPay wxPay;

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String curpage = "",pagesize="",cxmc="";
            String xmxx="",sffk="",sjh="",sftk="";
            TCzy tCzy = gettCzyDao().selectById(loginId);
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cxmc")) {
                cxmc = jsonObject.getString("cxmc");
            }
            if (jsonObject.containsKey("xmxx")) {
                xmxx = jsonObject.getString("xmxx");
            }
            if (jsonObject.containsKey("sffk")) {
                sffk = jsonObject.getString("sffk");
            }
            if (jsonObject.containsKey("sjh")) {
                sjh = jsonObject.getString("sjh");
            }
            if (jsonObject.containsKey("sftk")) {
                sftk = jsonObject.getString("sftk");
            }
            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "10";

            QueryWrapper<StampCardOrder> queryWrapper = new QueryWrapper<>();
            Page<StampCardOrder> page = new Page<>( Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            //找出操作员所在机构维护的项目
            List<StampXm> stampXmList = new ArrayList<>();
            //找出操作员所在机构维护的项目
            stampXmList = stampXmMapper.selectList(new QueryWrapper<StampXm>().eq("t_xzjg_id",tCzy.getXzjgId()).eq("state","1"));
            String ids = "";
            // 使用增强的 for 循环遍历原始列表
            for (StampXm stampXm : stampXmList) {
                ids+=String.valueOf(stampXm.getId())+",";
            }
            if (ids.length()>0) {
                ids=ids.substring(0,ids.length()-1);
                ids = "("+ids+")";
            }else{
                return new ResultInfo(500,"没有任何数据！",null);
            }
            if (StringUtils.isEmpty(xmxx)) {
                queryWrapper.apply(" hd_id in (select id from stamp_hd where xm_id in "+ids+")");
            }else{
                queryWrapper.apply(" hd_id in (select id from stamp_hd where xm_id="+xmxx+")");
            }
            if (!StringUtils.isEmpty(sftk)){
                queryWrapper.eq("istk",sftk);
            }
            if (!StringUtils.isEmpty(sffk)){
                queryWrapper.eq("isfk",sffk);
            }
            if (!StringUtils.isEmpty(sjh)){
                queryWrapper.like("lxdh_jsm",sjh);
            }
            queryWrapper.eq("scbz","0");
            queryWrapper.orderByDesc("id");

            IPage<StampCardOrder> stampCardOrderIPage =null;
            stampCardOrderIPage = stampCardOrderMapper.getStampCardOrderLPage(page,queryWrapper);

            ListInfo<StampCardOrder> stampCardOrderListInfo = new ListInfo<>();
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(stampCardOrderIPage.getTotal());
            pageInfo.setCurPage(stampCardOrderIPage.getCurrent());
            pageInfo.setPageSize(stampCardOrderIPage.getSize());
            pageInfo.setPageTotal(stampCardOrderIPage.getPages());

            stampCardOrderListInfo.setPageInfo(pageInfo);
            List<StampCardOrder> stampCardOrderList = stampCardOrderIPage.getRecords();
            // 循环遍历 List 并改变每个对象的 age 属性
            for (StampCardOrder stampCardOrder : stampCardOrderList) {
                stampCardOrder.setUrlId(ToolBean.getEncode(stampCardOrder.getId()));
            }
            stampCardOrderListInfo.setListInfo(stampCardOrderList);
            stampCardOrderListInfo.setUserId(loginId);

            //查询条件的值
            Map<String,Object> cxtjMap = new HashMap<>();
            cxtjMap.put("sjh",sjh);
            cxtjMap.put("xmxx",xmxx);
            cxtjMap.put("sffk",sffk);
            cxtjMap.put("sftk",sftk);
            cxtjMap.put("stampXmList",stampXmList);

            //返回前端的内容
            Map<String,Object> rtnMap = new HashMap<>();
            rtnMap.put("cxjg",stampCardOrderListInfo);
            rtnMap.put("cxtj",cxtjMap);

            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Transactional
    public ResultInfo tk(String loginId, Map<String, Object> map){
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String order_id = "";
            TCzy tCzy = gettCzyDao().selectById(loginId);
            if (jsonObject.containsKey("order_id")) {
                order_id = jsonObject.getString("order_id");
            }
            if (StringUtils.isEmpty(order_id)){
                return new ResultInfo(500,"订单号丢失！",null);
            }
            StampCardOrder stampCardOrder = stampCardOrderMapper.getById(Long.parseLong(order_id));

            if (!tCzy.getXzjgId().equals(stampCardOrder.getStampHd().getTXzjgId())){
                return new ResultInfo(500,"该用户参与的活动非本机构维护的活动！",null);
            }
            //先处理退款逻辑，退款逻辑成功后，再调用退款
            if (null!=stampCardOrder.getTWxOrder()){
                ResultInfo resultInfo = dealDdxxByTk(stampCardOrder.getTWxOrder(),tCzy.getId());
                if (resultInfo.getCode()==200){
                    //开始退款
                    ResultInfo resultInfo1  = wxPay.wxTk(stampCardOrder.getTWxOrder().getSendOutTradeNo());
                    return backRtn(new ResultInfo(0, "成功返回！",resultInfo1),loginId);
                }else{
                    return backRtn(new ResultInfo(0, "成功返回！",resultInfo),loginId);
                }
            }else{
                return new ResultInfo(500,"没有获取到微信支付订单！",null);
            }
        }
    }

    @Transactional
    public ResultInfo fhdj(String loginId, Map<String, Object> map){
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String id = "",yjhm="";
            TCzy tCzy = gettCzyDao().selectById(loginId);
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("yjhm")) {
                yjhm = jsonObject.getString("yjhm");
            }
            if (StringUtils.isEmpty(id)){
                return new ResultInfo(500,"订单号丢失！",null);
            }

            if (StringUtils.isEmpty(yjhm)){
                return new ResultInfo(500,"邮件号码丢失！",null);
            }

            id = ToolBean.getDecode(id);

            StampCardOrder stampCardOrder = stampCardOrderMapper.getById(Long.parseLong(id));

            if (!tCzy.getXzjgId().equals(stampCardOrder.getStampHd().getTXzjgId())){
                return new ResultInfo(500,"该用户参与的活动非本机构维护的活动！",null);
            }

            stampCardOrder.setIsfh("1");
            stampCardOrder.setFhdjrq(ToolBean.getToday());
            stampCardOrder.setFhdjry(tCzy.getId());
            stampCardOrder.setYjhm(yjhm);
            stampCardOrderMapper.updateById(stampCardOrder);


            return backRtn(new ResultInfo(0, "成功返回！",null),loginId);
        }
    }

    /**
     * 处理订单退款逻辑
     * @return
     */
    public ResultInfo dealDdxxByTk(TWxOrder tWxOrder,Long tkCzyId)
    {
        TWxOrder wxOrder1 = new TWxOrder();
        StampCardOrder stampCardOrder = new StampCardOrder();
        String rtn = "";
        String id = "";
        String tname = "";
        try {
            wxOrder1 = tWxOrderDao.selectById(tWxOrder.getLsh());
            stampCardOrder = stampCardOrderMapper.selectById(tWxOrder.getZblsh());
            String ywclState = wxOrder1.getTkywclState();
            if (StringUtils.isEmpty(ywclState)) ywclState = "0";
            if (ywclState.equals("1"))
            {
                return new ResultInfo(500, "退款业务已经完成，不要重复执行！", null);
            }else{
                ToolBean.info("开始处理stamp_card_order[订单主键："+wxOrder1.getZblsh()+"]退款业务逻辑...begin");
                tWxOrderDao.updateWxOrderTkbz(tWxOrder.getLsh()); //订单标志
                ToolBean.info("开始处理stamp_card_order[订单主键："+wxOrder1.getZblsh()+"]更新订单退款标志开始");
                int asl = stampCardOrderMapper.updateTkbz(wxOrder1.getZblsh(),tkCzyId, ToolBean.getToday());
                ToolBean.info("开始处理stamp_card_order[订单主键："+wxOrder1.getZblsh()+"]更新订单退款标志结束[更新数据条数"+asl+"]");
                return new ResultInfo(200, "成功！", null);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            ToolBean.info("dealDdxxByTk发生错误！"+e.toString());
            throw new RuntimeException("订单退款业务处理发生错误！"+e.toString());
        }
    }
}
